
package at.tugraz.kmi.css.commons;

import java.io.UnsupportedEncodingException;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;

import javax.swing.JTextArea;

public class TextAreaLogHandler extends StreamHandler {

	private final JTextArea	textarea;

	public TextAreaLogHandler(JTextArea t, Formatter formatter) {
		super(System.out, formatter);
		textarea = t;
		try {
			super.setEncoding("UTF-8"); //$NON-NLS-1$
		} catch (SecurityException e) {
			throw new IllegalStateException(e);
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}

	boolean	doneHeader;

	@Override
	public synchronized void publish(LogRecord record) {
		if (!isLoggable(record)) {
			return;
		}
		String msg;
		try {
			msg = getFormatter().format(record);
		} catch (Exception ex) {
			// We don't want to throw an exception here, but we
			// report the exception to any registered ErrorManager.
			reportError(null, ex, ErrorManager.FORMAT_FAILURE);
			return;
		}

		try {
			if (!doneHeader) {
				textarea.append(getFormatter().getHead(this));
				doneHeader = true;
			}
			textarea.append(msg);
			textarea.setCaretPosition(textarea.getDocument().getLength());
		} catch (Exception ex) {
			// We don't want to throw an exception here, but we
			// report the exception to any registered ErrorManager.
			reportError(null, ex, ErrorManager.WRITE_FAILURE);
		}
	}

}